package com.kiku.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.kiku.common.UserQuery;
import com.kiku.domain.po.Address;
import com.kiku.domain.po.User;
import com.kiku.dto.PageDTO;
import com.kiku.mapper.UserMapper;
import com.kiku.service.UserService;
import com.kiku.vo.AddressVo;
import com.kiku.vo.UserVo;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author kiku
 * @Date 2024/6/12 11:20
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public UserVo queryUserAndAddressById(Long userId) {
        User user = getById(userId);
        if (user == null) {
            return null;
        }
        //查收货地址
        List<Address> list = Db.lambdaQuery(Address.class).eq(Address::getUserId, user).list();
        //hutoool工具箱
        UserVo userVo = BeanUtil.copyProperties(user, UserVo.class);
        List<AddressVo> addresses = BeanUtil.copyToList(list, AddressVo.class);
        userVo.setAddresses(addresses);
        return userVo;
    }

    @Override
    public PageDTO<UserVo> queryUsersPage(UserQuery query) {
        Page<User> page = query.toMpPageDefaultSortByCreateTimeDesc();
        page(page);
        return PageDTO.of(page, user -> {
            // 拷贝属性到VO
            UserVo vo = BeanUtil.copyProperties(user, UserVo.class);
            // 用户名脱敏
            String username = vo.getUsername();
            vo.setUsername(username.substring(0, username.length() - 2) + "**");
            return vo;
        });
    }
}
